package com.ikas.ai.server.error;

import com.ikas.ai.consts.Consts;
import com.ikas.ai.handle.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 能拦截404、抛异常、参数类型异常等情况，但是隐藏了原始请求等信息
 * 全局异常转到/error，然后在这里被拦截了
 * @author unknow
 */
// @Controller
public class MainSiteErrorController implements ErrorController {

    private final Logger logger = LoggerFactory.getLogger(MainSiteErrorController.class);

    @RequestMapping("/error")
    @ResponseBody
    public String handleError(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        logger.error(String.format("URL:%s, Err:%s", request.getRequestURI(), e.getMessage()), e);
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        JsonResult result = new JsonResult();
        if (statusCode != null && statusCode == 404) {
            result.setMessage(String.format("[%d] Page not found", statusCode));
        } else if (statusCode != null && statusCode == 500) {
            Exception obj = (Exception) request.getAttribute("javax.servlet.error.exception");
            result.setMessage(String.format("[%d] %s", statusCode, obj.getCause().getMessage()));
        } else {
            result.setMessage(String.format("[%d] Unknown Error", statusCode));
        }
        PrintWriter writer;
        response.setCharacterEncoding(Consts.CHART_SET);
        response.setContentType(Consts.CONTENT_TYPE);
        try {
            result.setRemark("MainSiteErrorController");
            writer = response.getWriter();
            writer.print(result.toJSON());
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
        return null;
    }

    @Override
    public String getErrorPath() {
        return null;
    }
}